Skip to content

Read Postgres tables through pg_hydradb with a read-only store - #708

Merged
arrry-hydraDB merged 1 commit into
adityamishra/oss-136-store-hooksfrom
adityamishra/oss-136-pg-store
Dec 4, 2026
Merged

arrry-hydraDB merged 1 commit into
adityamishra/oss-136-store-hooksfrom
adityamishra/oss-136-pg-store

Conversation

@adityamishra-hydradb

@adityamishra-hydradb adityamishra-hydradb commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

2/5 of #706. Adds PgHydraDBStore, a read-only store over Postgres tables that a pg_hydradb graph registers, behind the selfgraph[postgres] extra.
Rows are entities, edge rows are current relations, and every write raises read_only_store. Python only; 3/5 ports it to TypeScript, and 5/5 adds the docs page.

Implementation details

Door: one-way
New public store class, extra, entity and relation id forms (person:1, relation:works_at:10), and the docs contract for what the store runs.

Cleanup: none

What to delete:

Decisions

  • Driver (decided by the maintainers on 2026-12-05): asyncpg (asyncpg>=0.30). It is native asyncio like the other stores, speaks the binary protocol, and binds $1 parameters. 0.30 added the pool reset hook, which lets the pool return a connection with no RESET ALL or other reset statement on the user's server.
  • Access contract: each connection starts with default_transaction_read_only=on and statement_timeout (10 s default) as startup settings, so every statement runs read-only and no SET is sent. Only fixed statements run: registry reads (hydradb.graphs, graph_vertex_tables, graph_edge_tables with their catalog rows), hydradb.reachable_edges, key lookups WHERE <key> = ANY(...), and the name lookup WHERE <name> ILIKE $1 LIMIT $2. Identifiers come only from the registry and are quoted; values are always bound. Key lists bind as one JSON parameter so the driver runs no type introspection query.
  • One hop is one reachable_edges call with max_depth 1, so retrieve, neighbors, and find_path keep their own walk and tie-breaking. paths_from and paths_between are not used: their tie-breaking differs from find_path, so results would change between stores. A walk that pg_hydradb cuts is split in halves until one row is cut alone; that row calls mark_partial. 4/5 walks such a row alone on later reads.
  • Seeding uses the seed_candidates hook from 1/5: one ILIKE lookup per table and query word, up to seed_limit (200) rows each, then the usual BM25.
  • Types come from the pg_hydradb labels, named as Schema.from_tables names a table (person is Person, works_at is WORKS_AT). draft_schema() returns them with each table as a synonym and a mapping.
  • Display name: names={label: column}, else the first text column called name, full_name, display_name, title, label, login, or username, else the first text column. A NULL name shows the key.
  • A read that would scan every row (entities.list, relations.list, counts, raw Cypher) raises unsupported_read instead of reading the tables in full.
  • initialize runs once behind a lock; every read waits for the registry. A failed first connect releases the pool without closing the store, so a later call can retry. An edge label or kind whose type Self Graph reserves (PREFERS, HAS_PROFILE, ...) fails with graph_unavailable, since _ops would hide those relations.
  • A store serves one namespace (namespace=, default default); a read for another raises ValidationError, so two graphs with different namespaces cannot share one store and read each other's rows.
  • Integer keys cover the full signed 64-bit range. A relation id is relation:<edge label>:<key>; only that one prefix is stripped, so a vertex or edge label named relation still works.
  • Errors show the URI without its query string, and hide a password query parameter as well as the user and password. A URI with an unencoded /, ?, #, @, [, or ] in its user or password is refused at construction, before anything can echo it.
  • The docs page for the store is in 5/5, to keep this PR under 1,000 lines.
  • CI (decided by the maintainers on 2026-12-05): #729 adds the CI job postgres. It builds pg_hydradb from a pinned hydradb commit and runs these gated tests of both SDKs on Postgres 16 and 17. No image goes to a registry.
  • check_answerable (decided by the maintainers on 2026-12-05): it stays refused on this store with unsupported_read, because it must read every row. No version that checks only seed candidates. The docs page lists it under "What is refused".
  • draft_schema reads the pg_hydradb registry and the Postgres catalog, never user rows. #729 changes the AGENTS.md rule to match: a schema draft may read a store's own catalog and registry, never user rows.

Validation

Local only, on throwaway Postgres 16.16, 17, and 18.7 in Docker with pg_hydradb built from hydra-db/hydradb main. Raw outputs are kept locally in selfgraph-oss136-proof/.

  • Proof on main (A): from selfgraph.stores.pg_hydradb import PgHydraDBStore raises ModuleNotFoundError; pip install "selfgraph-0.2.2-py3-none-any.whl[postgres]" warns selfgraph 0.2.2 does not provide the extra 'postgres'; the docs have no Postgres mention.
  • New tests/test_pg_hydradb_store.py (skipped unless SG_PG_HYDRADB_URI names a Postgres with pg_hydradb) passes on PG 16, 17, and 18. It also covers the review findings: bigint keys at both ends of the range, labels named relation, a reserved prefers label, an exact name behind more substring matches than seed_limit, concurrent first reads, and a retry after the graph is registered.
  • E2E A/B, the same script on main and on the branch:
Scenario A (main) B (branch)
connect + schema draft ModuleNotFoundError Company, Person, Project, Topic; CONTRIBUTES_TO, MENTORS, SUBTOPIC_OF, WORKS_AT
retrieve("who works at Acme") ModuleNotFoundError Ann Lee and Chloé Durand WORKS_AT Acme
retrieve(entity_ids=["person:1"]) ModuleNotFoundError person:1 and its 4 neighbours
neighbors("person:1") ModuleNotFoundError 4 entities at distance 1, truncated false
find_path("person:2", "company:acme") ModuleNotFoundError MENTORS person:1, WORKS_AT company:acme
write attempt ModuleNotFoundError read_only_store
missing graph ModuleNotFoundError graph_unavailable, not registered
paused graph (needs_refresh) ModuleNotFoundError graph_unavailable, is paused
hub with 5,999 edges ModuleNotFoundError neighbors, retrieve, and find_path report truncated: true
row the app inserts ModuleNotFoundError seen on the next retrieve
reader role grants SELECT only SELECT only
entities.list() ModuleNotFoundError unsupported_read
empty graph ModuleNotFoundError no_seeds_matched
  • Security: question text with '; DROP TABLE ..., %, _, \, and a UNION gives no seeds or normal seeds; entity and relation ids with SQL return None or not_found; a graph registered over a schema, tables, columns, and a label full of quotes and DROP text reads correctly; row counts are unchanged after each. A login with INSERT, UPDATE, and DELETE grants still only reads; the same session settings refuse a raw INSERT with 25006 cannot execute INSERT in a read-only transaction. A login that row-level security applies to gets graph_unavailable from pg_hydradb on a walk. A wrong password gives store_auth_failed without the password. The statement log (log_statement=all) of the final run holds only the four allowed shapes.
  • Stress, 1M people, 10k companies, 3M edges (one company with 50,094 employees), 40 random samples: with a trigram index on the name columns, retrieve p50 289 ms, p95 475 ms; neighbors p50 4.6 ms, p95 8.4 ms; find_path p50 42 ms, p95 3.8 s (paths through the 50k hub). Name lookup p50 5.5 ms, p95 7.1 ms with the index, p95 296 ms without. A 20 ms statement_timeout gives TransientError store_busy in 0.07 s. 50 concurrent retrieves on a pool of 4: 0 errors, at most 4 connections, 0 left after close.
  • Docs repro (docs land in 5/5): a clean venv with the built wheel followed the docs section block by block; every step passed.
  • Full Python suite on embedded Kuzu: A 1743 passed, 39 skipped; B 1750 passed, 48 skipped, 0 failed. precheck, make probes (secret_echo clean), ruff: precheck --base 1/5: all checks passed, with one warning: the store's error text gets conformance cases in 5/5, once both SDKs have the store. make probes: plan_apply, secret_echo, and unmerge_order pass; parity_table fails the same way on main and on the branch (vitest cannot parse a .scm query file in this environment). ruff check and ruff format --check: clean.

Limits

  • A row with more than 5,000 edges is read partially (pg_hydradb's limit), and pg_hydradb still loads all of its edges, about 0.5 s for 50,000.
  • check_answerable, suggest_schema, namespaces, and full listings raise unsupported_read.
  • A text key is addressable by id only in id form (lowercase, no spaces), since entity ids are canonicalised.
  • Rows carry no properties beyond the name, no sources, and no history.
  • CI: when this PR merged, CI skipped the new tests. #729 adds the job that runs them (see Decisions).

Linked issue

Closes #706

AI Assistance

Model Effort
Claude Opus 5.5 High

Checklist

  • Implements an issue a maintainer has /approved.
  • Small and scoped to that issue.
  • New errors have a code and hint, the same on API, CLI, and MCP in both SDKs (see AGENTS.md).
  • Breaking changes described below, or none.

Breaking changes

None.

🤖 Generated with Claude Code

@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@hydra-mira-review

hydra-mira-review Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Mira score 5/5 · 🟢 Good to merge

  • No findings in the code.
  • Confirm outside this PR: A compatible pg_hydradb extension, A registered, active graph and a reader login.
  • Read these high-risk changes closely: Open a bounded pool with read-only sessions, Build graph types from the registry and bind one namespace and 2 more.

Applications can read existing PostgreSQL tables as graph entities and relations through a new read-only Python store. The PR adds optional installation support, database fixtures, and tests for reads and errors.

Before this ships · 2 to confirm
  • ❔ A compatible pg_hydradb extension (contract), needed in The application's Postgres database. The fixture installs pg_hydradb, but no minimum released version establishes the registry and walk contract. Install a compatible extension before enabling the store and establish the minimum supported release.
  • ❔ A registered, active graph and a reader login (schema), needed in The application's Postgres database. tests/fixtures/pg_hydradb_work.sql demonstrates graph registration and reader grants; production registration and permissions are not established. Register the application tables, refresh any paused graph, and grant the reader required schema and SELECT access before opening the store.
How this PR works · 8 changes, 4 high risk, 3 medium risk, 1 low risk

Applications can query existing Postgres rows as a graph without copying them into another store. This PR adds a Python store that reads tables registered with pg_hydradb and uses existing retrieval algorithms. It refuses writes and unbounded reads, while leaving TypeScript support and documentation to later parts of the stack.

1. Open a bounded pool with read-only sessions · 🔴 high risk · pyproject.toml +1

Python callers gain a Postgres store through the optional postgres extra. Connections start read-only, default to a 10-second statement timeout, and share a pool capped at four connections.

Risk: Incorrect session settings could allow writes or leave application queries running beyond the configured timeout.

Check:

  • Check that a login with write grants still cannot write through a connection using these startup settings.
  • Check concurrent first reads and retry initialization after registering a previously missing graph.

How it works:

  1. initialize serializes startup behind a lock and imports the optional driver.
  2. initialize supplies startup settings and _keep_session suppresses pool reset statements.
  3. A registry failure closes the pool without permanently closing the store, allowing another initialization attempt.
  4. close waits for startup before releasing the pool.

What it touches:

  • src/selfgraph/client.py: SelfGraph.initialize.
  • src/selfgraph/client.py: SelfGraph.close.
  • Python construction through selfgraph.stores.pg_hydradb.PgHydraDBStore.
  • SelfGraph initialization and context management.
  • Sessions read application-owned tables without creating graph storage, indexes, or migrations.

In pyproject.toml:22, pg_hydradb.py:142-208, pg_hydradb.py:295-323 and 1 more.

2. Build graph types from the registry and bind one namespace · 🔴 high risk · src/selfgraph/stores/pg_hydradb.py

Registered tables become entity and relation types, with display columns selected from configuration or text-column defaults. Reads of application rows require the store's configured namespace.

Risk: Incorrect namespace or registry handling could expose another graph's rows or assign records the wrong types.

Check:

  • Read through two graph objects sharing one store but using different namespaces.
  • Check schema drafts for configured names, NULL names, kind columns, and reserved relation types.

How it works:

  1. _load_registry rejects missing graphs, paused graphs, and tables without SELECT access.
  2. _load_registry derives types from labels and adds table synonyms and mappings.
  3. draft_schema exposes those types, excluding relation types stored dynamically in a kind column.
  4. _open checks the namespace; _allowed rejects relation types reserved for internal graph records.

What it touches:

  • src/selfgraph/stores/pg_hydradb.py: _nodes.
  • src/selfgraph/stores/pg_hydradb.py: _named.
  • src/selfgraph/stores/pg_hydradb.py: _adjacent.
  • tests/test_pg_hydradb_store.py: test_entity_ids_neighbors_paths_and_the_schema_draft_read_the_tables.
  • First store initialization.
  • draft_schema().
  • The constructor's graph, names, and namespace arguments.
  • Registry metadata is cached for the store's lifetime; application rows remain in their original tables.

In pg_hydradb.py:39-58, pg_hydradb.py:210-293.

3. Read entities and current relations directly by row key · 🟠 medium risk · src/selfgraph/stores/pg_hydradb.py

Existing rows become addressable entities and current relations without an import step. Entity IDs use person:1; relation IDs use relation:works_at:10.

Risk: Incorrect key conversion or endpoint mapping would return missing records or connect entities incorrectly in retrieval results.

Check:

  • Read both signed 64-bit endpoints, a UUID key, and vertex and edge labels named relation.
  • Insert a row through the application and confirm it appears on the next read.

In pg_hydradb.py:80-140, pg_hydradb.py:367-409, pg_hydradb.py:450-492 and 3 more.

4. Find seed candidates with bounded name lookups · 🟠 medium risk · src/selfgraph/stores/pg_hydradb.py

Questions can find relevant rows without listing every entity. Name lookups use escaped ILIKE patterns, returning at most 200 rows per table and pattern by default.

Risk: Incorrect escaping or candidate selection would omit relevant rows and produce incomplete answers or failed name matches.

Check:

  • Find an exact name after more substring matches than seed_limit.
  • Check names containing literal %, _, and backslashes.

In pg_hydradb.py:89-95, pg_hydradb.py:411-448.

5. Walk one hop at a time and report incomplete results · 🟠 medium risk · src/selfgraph/stores/pg_hydradb.py

Graph reads expand existing rows through one-hop database walks while retaining the SDK's traversal and path selection. Results report truncation when one seed exceeds the database walk limit.

Risk: Incorrect direction handling or truncation propagation would omit neighbors or paths without clearly warning callers.

Check:

  • Compare incoming, outgoing, and bidirectional paths on the fixture graph.
  • Check a multi-seed walk containing a row with more than 5,000 edges and a subsequent complete walk.

Why: Using one-hop reads preserves existing traversal order instead of adopting the database's path selection.

In pg_hydradb.py:41-44, pg_hydradb.py:59-63, pg_hydradb.py:494-529 and 2 more.

6. Refuse writes and reads that require full listings · 🔴 high risk · src/selfgraph/stores/pg_hydradb.py

The new store rejects write primitives and write transactions with read_only_store. Full listings, counts, and raw Cypher raise unsupported_read; child-record reads return no records.

Risk: An incomplete refusal boundary could expose an unsupported operation or allow unintended writes to application tables.

Check:

  • Compare _WRITES with the store write contract, including bulk operations and transactions.
  • Check that full listings and namespace counts fail with unsupported_read.

How it works:

  1. _refuse supplies rejecting implementations for every method listed in _WRITES.
  2. transaction rejects entry before yielding a writer.
  3. match_nodes requires IDs, while match_edges requires endpoints.

What it touches:

  • src/selfgraph/client.py: SelfGraph.run_cypher.
  • src/selfgraph/_ops.py: list_entities.
  • src/selfgraph/_ops.py: list_relations.
  • tests/test_pg_hydradb_store.py: test_writes_and_full_scans_are_refused_with_a_code.
  • Entity and relation write APIs.
  • insert.facts().
  • entities.list() and relations.list().
  • namespaces() and run_cypher().
  • Application tables remain owned and modified by the application; the store creates no sources, profiles, or history.

In pg_hydradb.py:64-77, pg_hydradb.py:478-485, pg_hydradb.py:604-609 and 1 more.

7. Map Postgres failures to coded, redacted errors · 🔴 high risk · src/selfgraph/stores/pg_hydradb.py

Postgres failures become SDK errors with stable codes, including retryable statement timeouts. Connection messages omit URI query strings and mask credentials before reaching callers.

Risk: Incorrect redaction could expose database credentials in errors returned to applications or recorded in logs.

Check:

  • Check authentication and connection errors with encoded credentials and a password query parameter.
  • Check that a cancelled statement produces retryable store_busy.

How it works:

  1. _error maps SQLSTATE values to connection, authentication, database, timeout, and graph errors.
  2. _redact applies URI masking and removes encoded and decoded password query parameters.
  3. Construction rejects unencoded user information before passing the URI to the driver.

What it touches:

  • src/selfgraph/stores/pg_hydradb.py: initialize.
  • src/selfgraph/stores/pg_hydradb.py: _query.
  • tests/test_errors.py: test_a_postgres_password_in_the_uri_query_stays_out_of_errors.
  • Any store connection or SQL read.
  • Public errors carry existing SDK codes and hints instead of raw driver failures.

In pg_hydradb.py:325-365.

  1. Supporting changes · 🟢 low risk · tests in test_errors.py:224-283, test_errors.py:492-502, test_pg_hydradb_store.py:1-180 and 1 more.

Questions for the author:

  • Which released pg_hydradb version guarantees the registry columns and reachable_edges response shape used here?
Requirement check · 13 met, 2 for another PR · from the PR description
  • ✅ Add a Python read-only Postgres store behind the optional postgres extra (met). PgHydraDBStore is available from its store module; pyproject.toml declares asyncpg>=0.30.
  • ✅ Use read-only startup settings, bounded statements, quoted identifiers, and bound values without pool reset SQL (met). initialize, _keep_session, _ident, and _Table.by_keys implement the stated SQL access contract.
  • ✅ Read application rows as entities and edge rows as current relations (met). _nodes and _edge_rows fetch live rows; relation properties use revision 1 and is_current=True.
  • ✅ Preserve SDK traversal and path selection through one-hop database walks (met). _walk uses only hydradb.reachable_edges with max_depth=1; no database path function is called.
  • ✅ Split truncated batches and mark results partial when one seed is still cut (met). _walk recursively halves seed batches and calls mark_partial for a truncated single seed.
  • ➖ Continue walking a truncated row on later reads (for another PR). The description assigns this behavior to part 4/5 of the stack.
  • ✅ Use bounded name lookups as candidates for existing BM25 scoring (met). seed_candidates uses _named; existing retrieval._entity_pages consumes the hook before seed scoring.
  • ✅ Draft types from labels and choose display names from configuration or text-column defaults (met). _load_registry builds mappings and synonyms; draft_schema exposes the result and _entity falls back to the key.
  • ✅ Reject every write and reads that require full listings (met). _WRITES and transaction reject writes; listing guards, count methods, and run_cypher raise unsupported_read.
  • ✅ Serialize initialization, release a failed registry connection, and permit retry (met). initialize uses _starting and closes the failed pool without setting _closed.
  • ✅ Reject reserved relation types and enforce one namespace per store (met). _allowed rejects reserved label and kind types; _open rejects another namespace before reading application rows.
  • ✅ Support signed 64-bit keys and labels named relation (met). _Table.key_of checks signed 64-bit bounds; _edge_rows removes exactly one relation: prefix.
  • ✅ Keep credentials and URI query strings out of connection errors (met). _error masks the displayed URI; _redact removes password query values and construction calls require_encoded_userinfo.
  • ✅ Expose names without additional row properties, sources, or history (met). _entity and _edge_rows encode empty properties and synthetic metadata; child_nodes returns no child records.
  • ➖ Port the store to TypeScript and add its documentation page (for another PR). The description assigns TypeScript to part 3/5 and documentation to part 5/5.
⚠️ Other open PRs change the same code · 1

Merge them in order, or check that they agree.

Comment @hydra-mira-review help for commands.

@hydra-mira-review hydra-mira-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mira Review Summary

PgHydraDBStore has several read-path issues: valid 19-digit bigint keys are discarded, rows under a vertex label named relation and relations with reserved type names disappear from reads, and substring candidates can hide exact entity-name matches. Concurrent first reads can expose an incomplete registry and leak duplicate pools; connection errors can expose URI query passwords, and CI skips all Postgres integration tests.

Key Issues

Issue Location
🔴 Concurrent initialization exposes an incomplete registry and can leak duplicate pools. src/selfgraph/stores/pg_hydradb.py:190
🔴 Valid 19-digit bigint entity and edge keys are silently discarded. src/selfgraph/stores/pg_hydradb.py:120
🔴 Capped substring candidates can hide an existing exact entity-name match. src/selfgraph/stores/pg_hydradb.py:372

Comment thread src/selfgraph/stores/pg_hydradb.py Resolved
Comment thread src/selfgraph/stores/pg_hydradb.py Resolved
Comment thread src/selfgraph/stores/pg_hydradb.py Resolved
Comment thread tests/test_pg_hydradb_store.py Resolved
Comment thread src/selfgraph/stores/pg_hydradb.py Resolved
Comment thread src/selfgraph/stores/pg_hydradb.py Resolved
Comment thread src/selfgraph/stores/pg_hydradb.py Resolved
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@hydra-mira-review hydra-mira-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mira Review Summary

Connection errors in src/selfgraph/stores/pg_hydradb.py may expose an unencoded database password.

Comment thread src/selfgraph/stores/pg_hydradb.py Resolved
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@hydra-mira-review hydra-mira-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mira Review Summary

Tenants sharing the PgHydraDBStore can read the same graph even when they use separate namespaces. This may expose one tenant's graph data to another.

Comment thread src/selfgraph/stores/pg_hydradb.py Resolved
@adityamishra-hydradb
adityamishra-hydradb force-pushed the adityamishra/oss-136-pg-store branch from fa32f08 to ec238e2 Compare December 4, 2026 21:37
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@hydra-mira-review hydra-mira-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mira Review Summary

Closing the store during initialization can raise an uncoded exception in src/selfgraph/stores/pg_hydradb.py.

Comment thread src/selfgraph/stores/pg_hydradb.py Resolved
@adityamishra-hydradb
adityamishra-hydradb force-pushed the adityamishra/oss-136-pg-store branch from ec238e2 to d2f0ffc Compare December 4, 2026 21:49
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@adityamishra-hydradb
adityamishra-hydradb force-pushed the adityamishra/oss-136-pg-store branch from d2f0ffc to 4d1d632 Compare December 4, 2026 22:00
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

Signed-off-by: adityamishra-hydradb <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@adityamishra-hydradb
adityamishra-hydradb force-pushed the adityamishra/oss-136-pg-store branch from 4d1d632 to d976b66 Compare December 4, 2026 22:11
@adityamishra-hydradb

Copy link
Copy Markdown
Collaborator Author

@hydra-mira-review review

@arrry-hydraDB arrry-hydraDB left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@arrry-hydraDB
arrry-hydraDB merged commit 9817904 into main Dec 4, 2026
51 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Read Postgres tables through pg_hydradb with a read-only store

2 participants